import axios from 'axios';

// 获取 token（兼容旧浏览器写法）
const getToken = () => {
    const token = localStorage.getItem('token');
    return (token && token.trim()) || null; // ✅ 兼容写法
};

// 创建 axios 实例
const service = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' }, // 显式设置默认头
    withCredentials: true
});

// 请求拦截器
service.interceptors.request.use(
    function(config) {
        const token = getToken();
        if (token && token !== '') {
            config.headers.Authorization = 'Bearer ' + token;
        } else {
            console.warn('[WARN] 未找到有效 Token');
            // ✅ 主动清理残留 Token
            if (localStorage.getItem('token')) {
                localStorage.removeItem('token');
            }
        }
        return config;
    },
    function(error) {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    function(response) {
        return response.data;
    },
    function(error) {
        // ✅ 兼容性错误状态判断
        if (error.response && error.response.status === 401) {
            console.log('[AUTH] 认证失效，跳转登录');
            localStorage.removeItem('token');
            delete service.defaults.headers.common['Authorization'];
            window.location.href = '/login'; 
        }
        return Promise.reject(error);
    }
);

// ✅ 统一退出方法（兼容旧浏览器）
export function forceLogout() {
    localStorage.removeItem('token');
    delete service.defaults.headers.common['Authorization'];
    window.location.href = '/login';
}

export function forceLogout4Admin() {
    localStorage.removeItem('token');
    delete service.defaults.headers.common['Authorization'];
    window.location.href = '/login-login';
}
export default service;